{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Note\n",
    "\n",
    "Please view the [README](https://github.com/eclipse/deeplearning4j/tree/master/dl4j-examples/tutorials/README.md) to learn about installing, setting up dependencies, and importing notebooks in Zeppelin"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Background"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this tutorial, we will apply a neural network model to a cloud detection application using satellite imaging data. The data is from NASA's Multi-angle Imaging SpectroRadiometer (MISR) which was launched in 1999. The MISR has nine cameras that view the Earth from nine different directions which allows the MISR to measure elevations and angular radiance signatures of objects. We will use the radiances measured from the MISR and features developed using domain expertise to learn to detect whether clouds are present in polar regions. This is a particularly challenging task due to the snow and ice covering the ground surfaces.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "import org.datavec.api.records.reader.impl.csv.CSVRecordReader;\n",
    "import org.deeplearning4j.eval.ROC;\n",
    "import org.deeplearning4j.nn.api.OptimizationAlgorithm;\n",
    "import org.deeplearning4j.nn.conf.NeuralNetConfiguration;\n",
    "import org.deeplearning4j.nn.conf.Updater;\n",
    "import org.deeplearning4j.nn.conf.layers.DenseLayer;\n",
    "import org.deeplearning4j.nn.weights.WeightInit;\n",
    "import org.nd4j.linalg.activations.Activation;\n",
    "import org.nd4j.linalg.api.ndarray.INDArray;\n",
    "import org.datavec.api.records.reader.RecordReader;\n",
    "import org.datavec.api.split.FileSplit;\n",
    "import org.deeplearning4j.datasets.datavec.RecordReaderMultiDataSetIterator;\n",
    "import org.deeplearning4j.nn.conf.layers.OutputLayer;\n",
    "import org.deeplearning4j.eval.Evaluation;\n",
    "import org.nd4j.linalg.dataset.api.iterator.MultiDataSetIterator;\n",
    "import org.nd4j.linalg.dataset.api.MultiDataSet;\n",
    "import org.deeplearning4j.nn.conf.ComputationGraphConfiguration;\n",
    "import org.nd4j.linalg.lossfunctions.LossFunctions;\n",
    "import org.deeplearning4j.nn.conf.graph.MergeVertex;\n",
    "import org.deeplearning4j.nn.graph.ComputationGraph;\n",
    "\n",
    "import org.nd4j.linalg.api.ndarray.INDArray;\n",
    "import java.io.File;\n",
    "import java.net.URL;\n",
    "import java.io.BufferedInputStream;\n",
    "import java.io.FileInputStream;\n",
    "import java.io.BufferedOutputStream;\n",
    "import java.io.FileOutputStream;\n",
    "import org.apache.commons.io.FilenameUtils;\n",
    "import org.apache.commons.io.FileUtils;\n",
    "import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;\n",
    "import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;\n",
    "import org.apache.commons.compress.archivers.tar.TarArchiveEntry;"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The data is taken from MISR measurements and expert features of 3 images of polar regions. For each location in the grid, there is an expert label whether or not clouds are present and 8 features (radiances + expert labels). Data from two images will comprise the training set and the left out image is in the test set.\n",
    "\n",
    "The data can be found in a tar.gz file located at the url provided below in the next cell. It is organized into two directories (train and test). In each directory there are five subdirectories: n1, n2, n3, n4, and n5. The data in n1 contains expert features and the label pertaining to a particular location in an image. n2, n3, n4, and n5 contain the expert features corresponding to the nearest locations to the original location. \n",
    "\n",
    "We will additionally use features from a location's nearest neighbors as features to feed into our model, because there are dependencies across neighboring locations. In other words, if a location's neighbors have a positive cloud label, it is more likely for the original location to have a positive cloud label as well. The reverse also applies as well. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "val DATA_URL = \"https://bpstore1.blob.core.windows.net/tutorials/Cloud.tar.gz\"\n",
    "val DATA_PATH = FilenameUtils.concat(System.getProperty(\"java.io.tmpdir\"), \"dl4j_cloud/\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download Data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To download the data, we will create a temporary directory that will store the data files, extract the tar.gz file from the url, and place it in the specified directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "val directory = new File(DATA_PATH)\n",
    "directory.mkdir() \n",
    "\n",
    "val archizePath = DATA_PATH + \"Cloud.tar.gz\"\n",
    "val archiveFile = new File(archizePath)\n",
    "val extractedPath = DATA_PATH + \"Cloud\" \n",
    "val extractedFile = new File(extractedPath)\n",
    "\n",
    "FileUtils.copyURLToFile(new URL(DATA_URL), archiveFile) \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " \n",
    "\n",
    "Next, we must extract the data from the tar.gz file, recreate directories within the tar.gz file into our temporary directory, and copy the files into our temporary directory. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "var fileCount = 0\n",
    "var dirCount = 0\n",
    "val BUFFER_SIZE = 4096\n",
    "\n",
    "val tais = new TarArchiveInputStream(new GzipCompressorInputStream( new BufferedInputStream( new FileInputStream(archizePath))))\n",
    "\n",
    "var entry = tais.getNextEntry().asInstanceOf[TarArchiveEntry]\n",
    "\n",
    "while(entry != null){\n",
    "    if (entry.isDirectory()) {\n",
    "        new File(DATA_PATH + entry.getName()).mkdirs()\n",
    "        dirCount = dirCount + 1\n",
    "        fileCount = 0\n",
    "    }\n",
    "    else {\n",
    "        \n",
    "        val data = new Array[scala.Byte](4 * BUFFER_SIZE)\n",
    "\n",
    "        val fos = new FileOutputStream(DATA_PATH + entry.getName());\n",
    "        val dest = new BufferedOutputStream(fos, BUFFER_SIZE);\n",
    "        var count = tais.read(data, 0, BUFFER_SIZE)\n",
    "        \n",
    "        while (count != -1) {\n",
    "            dest.write(data, 0, count)\n",
    "            count = tais.read(data, 0, BUFFER_SIZE)\n",
    "        }\n",
    "        \n",
    "        dest.close()\n",
    "        fileCount = fileCount + 1\n",
    "    }\n",
    "    if(fileCount % 1000 == 0){\n",
    "        print(\".\")\n",
    "    }\n",
    "    \n",
    "    entry = tais.getNextEntry().asInstanceOf[TarArchiveEntry]\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### DataSetIterators"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our next goal is to convert the raw data (csv files) into a DataSetIterator, which can then be fed into a neural network for training. We will first obtain the paths containing the raw data, which is in csv file format. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "val path = FilenameUtils.concat(DATA_PATH, \"Cloud/\") // set parent directory\n",
    "\n",
    "val trainBaseDir1 = FilenameUtils.concat(path, \"train/n1/train.csv\") \n",
    "val trainBaseDir2 = FilenameUtils.concat(path, \"train/n2/train.csv\")\n",
    "val trainBaseDir3 = FilenameUtils.concat(path, \"train/n3/train.csv\")\n",
    "val trainBaseDir4 = FilenameUtils.concat(path, \"train/n4/train.csv\")\n",
    "val trainBaseDir5 = FilenameUtils.concat(path, \"train/n5/train.csv\") \n",
    "\n",
    "val testBaseDir1 = FilenameUtils.concat(path, \"test/n1/test.csv\")\n",
    "val testBaseDir2 = FilenameUtils.concat(path, \"test/n2/test.csv\")\n",
    "val testBaseDir3 = FilenameUtils.concat(path, \"test/n3/test.csv\")\n",
    "val testBaseDir4 = FilenameUtils.concat(path, \"test/n4/test.csv\") \n",
    "val testBaseDir5 = FilenameUtils.concat(path, \"test/n5/test.csv\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We then will create two DataSetIterators to feed the data into a neural network. But first, we will initialize CSVRecordReaders to parse the raw data and convert it to record-like format. We create separate CSVRecordReaders for the original location and each nearest neighbor. Since the data is contained in separate RecordReaders, we will use a RecordReaderMultiDataSetIterator, which allows for multiple inputs or outputs. We then add the RecordReaders to the DataSetIterator using the addReader method of the DataSetIterator.Builder() class. We specify the inputs using the addInput method and the label using the addOutputOneHot method.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "val rrTrain1 = new CSVRecordReader(1);\n",
    "rrTrain1.initialize(new FileSplit(new File(trainBaseDir1)));\n",
    "val rrTrain2 = new CSVRecordReader(1);\n",
    "rrTrain2.initialize(new FileSplit(new File(trainBaseDir2)))\n",
    "\n",
    "val rrTrain3 = new CSVRecordReader(1);\n",
    "rrTrain3.initialize(new FileSplit(new File(trainBaseDir3)))\n",
    "\n",
    "val rrTrain4 = new CSVRecordReader(1);\n",
    "rrTrain4.initialize(new FileSplit(new File(trainBaseDir4)))\n",
    "\n",
    "val rrTrain5 = new CSVRecordReader(1);\n",
    "rrTrain5.initialize(new FileSplit(new File(trainBaseDir5)))\n",
    "\n",
    "\n",
    "val trainIter = new RecordReaderMultiDataSetIterator.Builder(20)\n",
    "        .addReader(\"rr1\",rrTrain1)\n",
    "        .addReader(\"rr2\",rrTrain2)\n",
    "        .addReader(\"rr3\",rrTrain3)\n",
    "        .addReader(\"rr4\",rrTrain4)\n",
    "        .addReader(\"rr5\",rrTrain5)\n",
    "        .addInput(\"rr1\", 1, 3)\n",
    "        .addInput(\"rr2\", 0, 2)\n",
    "        .addInput(\"rr3\", 0, 2)\n",
    "        .addInput(\"rr4\", 0, 2)\n",
    "        .addInput(\"rr5\", 0, 2)\n",
    "        .addOutputOneHot(\"rr1\", 0, 2)\n",
    "        .build();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same process is applied to the testing data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "val rrTest1 = new CSVRecordReader(1);\n",
    "rrTest1.initialize(new FileSplit(new File(testBaseDir1)));\n",
    "\n",
    "val rrTest2 = new CSVRecordReader(1);\n",
    "rrTest2.initialize(new FileSplit(new File(testBaseDir2)));\n",
    "\n",
    "val rrTest3 = new CSVRecordReader(1);\n",
    "rrTest3.initialize(new FileSplit(new File(testBaseDir3)));\n",
    "\n",
    "val rrTest4 = new CSVRecordReader(1);\n",
    "rrTest4.initialize(new FileSplit(new File(testBaseDir4)));\n",
    "\n",
    "val rrTest5 = new CSVRecordReader(1);\n",
    "rrTest5.initialize(new FileSplit(new File(testBaseDir5)));\n",
    "\n",
    "val testIter = new RecordReaderMultiDataSetIterator.Builder(20)\n",
    "        .addReader(\"rr1\",rrTest1)\n",
    "        .addReader(\"rr2\",rrTest2)\n",
    "        .addReader(\"rr3\",rrTest3)\n",
    "        .addReader(\"rr4\",rrTest4)\n",
    "        .addReader(\"rr5\",rrTest5)\n",
    "        .addInput(\"rr1\", 1, 3)\n",
    "        .addInput(\"rr2\", 0, 2)\n",
    "        .addInput(\"rr3\", 0, 2)\n",
    "        .addInput(\"rr4\", 0, 2)\n",
    "        .addInput(\"rr5\", 0, 2)\n",
    "        .addOutputOneHot(\"rr1\", 0, 2)\n",
    "        .build();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Neural Net Configuration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that the DataSetIterators are initialized, we can now specify the configuration of the neural network. We will ultimately use a ComputationGraph since we will have multiple inputs to the network. MultiLayerNetworks cannot be used when there are multiple inputs and/or outputs. \n",
    "\n",
    "To specify the network architecture and the hyperparameters, we use the NeuralNetConfiguraiton.Builder class. We can add each input using the addLayer method of the class. Because the inputs are separate, the addVertex method is used to add a MergeVertex to the network. This vertex will merge the outputs from the previous input layers into a combined representation. Finally, a fully connected layer is applied to the merged output, which passes the activations to the final output layer.\n",
    "\n",
    "The other hyperparameters, such as the optimization algorithm, updater, number of hidden nodes, and etc are also specified in this block of code as well. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "val conf = new NeuralNetConfiguration.Builder()\n",
    "        .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)\n",
    "        .updater(Updater.ADAM)\n",
    "        .graphBuilder()\n",
    "        .addInputs(\"input1\", \"input2\", \"input3\", \"input4\", \"input5\")\n",
    "        .addLayer(\"L1\", new DenseLayer.Builder()\n",
    "            .weightInit(WeightInit.XAVIER)\n",
    "            .activation(Activation.RELU)\n",
    "            .nIn(3).nOut(50)\n",
    "            .build(), \"input1\")\n",
    "        .addLayer(\"L2\", new DenseLayer.Builder()\n",
    "            .weightInit(WeightInit.XAVIER)\n",
    "            .activation(Activation.RELU)\n",
    "            .nIn(3).nOut(50)\n",
    "            .build(), \"input2\")\n",
    "        .addLayer(\"L3\", new DenseLayer.Builder()\n",
    "            .weightInit(WeightInit.XAVIER)\n",
    "            .activation(Activation.RELU)\n",
    "            .nIn(3).nOut(50)\n",
    "            .build(), \"input3\")\n",
    "        .addLayer(\"L4\", new DenseLayer.Builder()\n",
    "            .weightInit(WeightInit.XAVIER)\n",
    "            .activation(Activation.RELU)\n",
    "            .nIn(3).nOut(50)\n",
    "            .build(), \"input4\")\n",
    "        .addLayer(\"L5\", new DenseLayer.Builder()\n",
    "            .weightInit(WeightInit.XAVIER)\n",
    "            .activation(Activation.RELU)\n",
    "            .nIn(3).nOut(50)\n",
    "            .build(), \"input5\")\n",
    "        .addVertex(\"merge\", new MergeVertex(), \"L1\", \"L2\", \"L3\", \"L4\", \"L5\")\n",
    "        .addLayer(\"L6\", new DenseLayer.Builder()\n",
    "            .weightInit(WeightInit.XAVIER)\n",
    "            .activation(Activation.RELU)\n",
    "            .nIn(250).nOut(125).build(), \"merge\")\n",
    "        .addLayer(\"out\", new OutputLayer.Builder()\n",
    "            .lossFunction(LossFunctions.LossFunction.MCXENT)\n",
    "            .weightInit(WeightInit.XAVIER)\n",
    "            .activation(Activation.SOFTMAX)\n",
    "            .nIn(125)\n",
    "            .nOut(2).build(), \"L6\")\n",
    "        .setOutputs(\"out\")\n",
    "        .pretrain(false).backprop(true)\n",
    "        .build();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model Training"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are now ready to train our model. We initialize our ComptutationGraph and loop over the number of epochs and call the fit method of the ComputationGraph to train our specified model. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "val model = new ComputationGraph(conf);\n",
    "model.init()\n",
    "for ( epoch <- 1 to 5) {\n",
    "    println(\"Epoch number: \" + epoch );\n",
    "    model.fit( trainIter );\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " \n",
    "To evaluate our model, we simply use the evaluateROC method of the ComptuationGraph class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "val roc = model.evaluateROC(testIter, 100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally we can print out the area under the curve (AUC) metric!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "autoscroll": "auto"
   },
   "outputs": [],
   "source": [
    "println(\"FINAL TEST AUC: \" + roc.calculateAUC());"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Spark 2.0.0 - Scala 2.11",
   "language": "scala",
   "name": "spark2-scala"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".scala",
   "mimetype": "text/x-scala",
   "name": "scala",
   "pygments_lexer": "scala",
   "version": "2.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
